package com.cgc.venus.server.app.controller;

import com.cgc.venus.server.app.bean.*;
import com.cgc.venus.server.app.inter.AppRepositoryService;
import com.cgc.venus.server.core.bean.response.VenusResponse;
import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.harbor.model.Tag;
import com.cgc.venus.server.core.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by xiaobin on 2017/9/25.
 */
@Api(value = "镜像管理", description = "镜像管理所对应服务的api")
@RequestMapping("/repository-admin")
@RestController
public class AppRepositoryController {
    @Autowired
    private AppRepositoryService appRepositoryService;

    @ApiOperation("私有空间镜像查询")
    @RequestMapping(value = "/private/repository", method = RequestMethod.GET)
    public VenusResponse<List<RepoBean>> repositoryQuery(@RequestParam(value = "queryKey", required = false) String queryKey,
                                                         @RequestParam(value = "spaceName", required = true) String spaceName) throws VenusException {
        List<RepoBean> obj = appRepositoryService.repoPrivateQuery(queryKey, spaceName);
        VenusResponse<List<RepoBean>> response = new VenusResponse<List<RepoBean>>(VenusResponseStatus.OK, "", obj);
        return response;
    }

    @ApiOperation("公有空间镜像查询")
    @RequestMapping(value = "/public/repository", method = RequestMethod.GET)
    public VenusResponse<List<RepoBean>> repoPublicQuery(@RequestParam(value = "queryKey", required = false) String queryKey,
                                                         @RequestParam(value = "spaceName", required = true) String spaceName) throws VenusException {
        List<RepoBean> obj = appRepositoryService.repoPublicQuery(queryKey, spaceName);
        VenusResponse<List<RepoBean>> response = new VenusResponse<List<RepoBean>>(VenusResponseStatus.OK, "", obj);
        return response;
    }

    @ApiOperation("镜像详细信息查询")
    @RequestMapping(value = "/image", method = RequestMethod.GET)
    public VenusResponse<List<RepoDetialBean>> imageDetialQuery(@RequestParam(value = "reponame", required = true) String reponame) throws VenusException {
        List<RepoDetialBean> obj = appRepositoryService.imageQuery(reponame);
        VenusResponse<List<RepoDetialBean>> response = new VenusResponse<List<RepoDetialBean>>(VenusResponseStatus.OK, "", obj);
        return response;
    }

    @ApiOperation("私有空间镜像删除")
    @RequestMapping(value = "/private/repository", method = RequestMethod.DELETE)
    public VenusResponse<Boolean> repositoryDelete(@RequestBody RepoDelBean repoDelBean) throws VenusException {
        boolean obj = appRepositoryService.repoDelete(repoDelBean.getRepoName(), repoDelBean.getTags());
        boolean f = false;
//        删除私有表中的记录
        if (obj) {
            f = appRepositoryService.repoSetPrivate(repoDelBean.getRepoName());
        }
        VenusResponse<Boolean> response = new VenusResponse<Boolean>(VenusResponseStatus.OK, "删除成功", obj);
        return response;
    }

    @ApiOperation("镜像版本信息查询")
    @RequestMapping(value = "/repository/repo-name/tag", method = RequestMethod.GET)
    public VenusResponse<Object> appTagsQuery(@RequestParam(value = "repoName", required = true) String repoName) throws VenusException {
        List<Tag> obj = appRepositoryService.appTagsQuery(repoName);
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK, "", obj);
        return response;
    }

    @ApiOperation("镜像设置为私有")
    @RequestMapping(value = "/repository/set", method = RequestMethod.DELETE)
    public VenusResponse<Boolean> repoSetPrivate(@RequestBody RepoDelBean repoDelBean) throws VenusException {

        boolean f = appRepositoryService.repoSetPrivate(repoDelBean.getRepoName());
        VenusResponse<Boolean> response = new VenusResponse<Boolean>(VenusResponseStatus.OK, "设置成功", f);
        return response;
    }

    @ApiOperation("镜像设置为公有")
    @RequestMapping(value = "/repository/set", method = RequestMethod.POST)
    public VenusResponse<Boolean> repoSetPublic(@RequestBody RepoDelBean repoDelBean) throws VenusException {
        boolean a = appRepositoryService.repoNameExist(repoDelBean.getRepoName());
        if (a) {
            throw new VenusException(VenusResponseStatus.MYSQL_DB_EXCEPTION, "镜像名称已存在");
        }
        boolean f = appRepositoryService.repoSetPublic(repoDelBean.getRepoName());
        VenusResponse<Boolean> response = new VenusResponse<Boolean>(VenusResponseStatus.OK, "设置成功", f);
        return response;
    }

    @ApiOperation("镜像统计查询")
    @RequestMapping(value = "/repository/stats", method = RequestMethod.GET)
    public VenusResponse<Object> repositoryStats(@RequestParam(value = "namespace", required = true) String namespace) throws VenusException {
        Map obj = new HashMap<>();
        obj.put("private", 10);
        obj.put("public", 4);
        obj.put("store", 20);
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK, "", obj);
        return response;
    }

    /*
    * 获得镜像版本说明
    * */
    @ApiOperation("获得镜像版本说明")
    @RequestMapping(value = "/image/version/described", method = RequestMethod.GET)
    public VenusResponse<Object> getImageVersionDescribed(@RequestParam("image") String image, @RequestParam("version") String version) throws VenusException {
        if (StringUtils.isBlank(image))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为空");
        if (StringUtils.isBlank(version))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像版本为空");
        ImageVersionDetailBean described = appRepositoryService.getImageVersionDescribed(image, version);
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK, "", described);
        return response;
    }

    /*
    * 新增镜像版本说明
    * */
    @ApiOperation("新增镜像版本说明")
    @RequestMapping(value = "/image/version/described", method = RequestMethod.POST)
    public VenusResponse<Object> addImageVersionDescribed(@RequestBody ImageVersionDetailBean imageVersionDetailBean) throws VenusException {
        int row = appRepositoryService.addImageVersionDescribed(imageVersionDetailBean);
        int code = VenusResponseStatus.OK;
        String message = "新增镜像:" + imageVersionDetailBean.getImage() + ":" + imageVersionDetailBean.getVersion() + ",版本描述,成功";
        if (row == 0) {
            code = VenusResponseStatus.HANDLE_ERROR;
            message = "新增镜像:" + imageVersionDetailBean.getImage() + ":" + imageVersionDetailBean.getVersion() + ",版本描述,失败";
        }

        VenusResponse<Object> response = new VenusResponse<Object>(code, message, "");
        return response;
    }

    /*
    * 修改镜像版本说明
    * */
    @ApiOperation("修改镜像版本说明")
    @RequestMapping(value = "/image/version/described", method = RequestMethod.PATCH)
    public VenusResponse<Object> editImageVersionDescribed(@RequestBody ImageVersionDetailBean imageVersionDetailBean) throws VenusException {
        int row = appRepositoryService.editImageVersionDescribed(imageVersionDetailBean);
        int code = VenusResponseStatus.OK;
        String message = "修改镜像:" + imageVersionDetailBean.getImage() + ":" + imageVersionDetailBean.getVersion() + ",版本描述,成功";
        if (row == 0) {
            code = VenusResponseStatus.HANDLE_ERROR;
            message = "修改镜像:" + imageVersionDetailBean.getImage() + ":" + imageVersionDetailBean.getVersion() + ",版本描述,失败";
        }
        VenusResponse<Object> response = new VenusResponse<Object>(code, message, "");
        return response;
    }

    /*
    * 获得镜像,所有版本的明细说明
    * */
    @ApiOperation("获得镜像版本说明")
    @RequestMapping(value = "/image/described", method = RequestMethod.GET)
    public VenusResponse<Object> getImageDescribed(@RequestParam("image") String image) throws VenusException {
        if (StringUtils.isBlank(image))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为空");
        List<ImageVersionDetailBean> list = appRepositoryService.getImageDescribed(image);
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK, "", list);
        return response;
    }

    /*
    * 上传镜像参数excel文件
    * */
    @ApiOperation(value = "镜像参数批量维护-接口", notes = "根据上传的excel文件批量维护镜像参数")
    @RequestMapping(value = "/images/para/upload", method = RequestMethod.POST)
    public VenusResponse<Object> setImagesParaByUploadFile(@RequestParam("namespace") String namespace, HttpServletRequest request) throws Exception {
        // 此接口支持上传多文件
        List<MultipartFile> multipartFileList = ((MultipartHttpServletRequest) request).getFiles("file");
        String result="";
        for (MultipartFile file : multipartFileList) {
            //String filePath = "D:\\downloadfile\\demo.xls";
            List<ImageParaBean> imageParaBeans = null;
            try {
                //imageParaBeans = ExcelUtil.importExcel(filePath, 1, 1, ImageParaBean.class);
                imageParaBeans = ExcelUtil.importExcel(file, 1, 1, ImageParaBean.class);
            } catch (Exception ex) {
                ex.printStackTrace();
                return new VenusResponse<Object>(VenusResponseStatus.OK, "文件格式错误,请按照模板上传正常的文件", "");
            }
            //List<ImageParaBean> imageParaBeans1 = ExcelUtil.importExcel(file, 1, 1, ImageParaBean.class);
            result = appRepositoryService.setImagePara(imageParaBeans, namespace);
            break;
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK, result, "");
        return response;
    }

    /*
    * 镜像参数下载
    * */
    @ApiOperation(value = "镜像参数下载-接口", notes = "镜像参数下载")
    @RequestMapping(value = "images/para/download", method = RequestMethod.GET)
    public void downloadImagesPara(@RequestParam("namespace") String namespace, HttpServletResponse response) throws VenusException {
        List<ImageParaBean> imageParaBeans = appRepositoryService.getImageParaByNamespace(namespace);
        //导出操作
        try {
            ExcelUtil.exportExcel(imageParaBeans, namespace + "_镜像参数列表", "镜像参数", ImageParaBean.class, namespace + "_镜像参数列表.xls", response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * 镜像参数下载
    * */
    @ApiOperation(value = "镜像参数模板下载-接口", notes = "镜像参数维护模板下载")
    @RequestMapping(value = "images/para/template/download", method = RequestMethod.GET)
    public void downloadImagesParaTemplate(HttpServletResponse response) throws VenusException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("ImagesParaSetTemplate.xls", "UTF-8"));
            InputStream ins = AppRepositoryController.class.getResourceAsStream("/ImagesParaSetTemplate.xls");
            //workbook.write(response.getOutputStream());
            OutputStream ops = response.getOutputStream();
            byte[] content = new byte[1024];
            int length = 0;
            while ((length = ins.read(content)) != -1) {
                ops.write(content, 0, length);
            }
            ops.flush();
            ops.close();
            ins.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
